<template>
  <ElConfigProvider :locale="zhCn">
    <div class="dynamic-form">
      <!-- <ElButton type="primary" @click="loading = !loading"> 加载中 </ElButton>

      <PaginatedTable
        v-loading="loading"
        :table-columns="tableColumns"
        :table-props="{
          height: '100%',
          rowKey: (row) => row.name,
          data: tableData,
        }"
        :filter="{
          filterBy: 'name',
        }"
        :pagination-props="{
          pageSize: 0,
        }"
      /> -->
      <DynamicForm
        ref="formRef"
        :model="formData"
        :rules="rules"
        :form-items="formItems"
      />
      <ElButton type="primary" style="margin: 10px 80px" @click="validate">
        验证
      </ElButton>
      <ElButton style="margin: 10px 80px" @click="resetFields">重置</ElButton>
      <ElButton
        type="primary"
        style="margin: 10px 80px"
        @click="openFormDialog"
      >
        打开函数式表单对话框
      </ElButton>
      <ElButton
        type="primary"
        style="margin: 10px 80px"
        @click="openFormDialog1"
      >
        打开函数式对话框
      </ElButton>
    </div>
  </ElConfigProvider>
</template>
<script setup lang="ts">
import { reactive, useTemplateRef, ref, h, useSlots, computed } from "vue";
import {
  ElInput,
  ElButton,
  ElSelect,
  ElRadioGroup,
  ElCheckboxGroup,
  type FormRules,
  ElMessage,
  ElConfigProvider,
  ElLink,
  ElTable,
  ElLoading,
} from "element-plus";
import {
  DynamicForm,
  openDialog,
  showContextMenu,
  PaginatedTable,
  itemType,
} from "./components/ElementPlusExtension";
import type {
  FormItem,
  TableColumn,
  FormItemOptionType,
} from "./components/ElementPlusExtension";
import { Coin, Delete, Edit } from "@element-plus/icons-vue";
import { zhCn } from "element-plus/es/locales.mjs";
import { nanoid } from "nanoid";

const loading = ref(false);
// document.addEventListener("contextmenu", (e) => {
//   e.preventDefault();
//   const { x, y } = e;
//   showContextMenu(
//     { x, y },
//     [
//       { label: "充值", id: 5, icon: Coin },
//       { label: "复制", id: 1, icon: Edit },
//       { label: "粘贴", id: 2 },
//       { label: "-" },
//       { label: "剪切", id: 3 },
//       { label: "删除", icon: Delete, disabled: true, id: 4 },
//     ],
//     (id) => {
//       console.log(id);
//     }
//   );
// });

const trstdata = "123,456,789";

const tableData = ref([
  { name: "张三", age: 18 },
  { name: "李四", age: 22 },
  { name: "王五", age: 30 },
  { name: "赵六", age: 25 },
  { name: "孙七", age: 28 },
  { name: "周八", age: 35 },
  { name: "吴九", age: 40 },
  { name: "郑十", age: 29 },
  { name: "冯十一", age: 31 },
  { name: "陈十二", age: 27 },
  { name: "褚十三", age: 33 },
  { name: "卫十四", age: 26 },
  { name: "蒋十五", age: 38 },
  { name: "沈十六", age: 34 },
  { name: "韩十七", age: 39 },
  { name: "杨十八", age: 36 },
  { name: "朱十九", age: 37 },
  { name: "秦二十", age: 41 },
  { name: "尤二十一", age: 42 },
  { name: "许二十二", age: 43 },
  { name: "许二十二", age: 43 },
  { name: "尤二十一", age: 42 },
  { name: "许二十二", age: 43 },
  { name: "许二十二", age: 43 },
]);

const tableColumns: TableColumn<(typeof tableData.value)[number]>[] = [
  {
    label: "姓名",
    prop: "name",
  },
  {
    align: "right",
    header: () => {
      return h(
        ElLink,
        {
          type: "primary",
          underline: "never",
          style: { onClick: () => {} },
        },
        () => "添加"
      );
    },
  },
];

const formRef = useTemplateRef<InstanceType<typeof DynamicForm>>("formRef");

const formData = reactive({
  name: "张三",
  home: "",
  age: undefined as number | undefined,
  sex: undefined as number | undefined,
  hobby: [] as number[],
  education: undefined as number | undefined,
  way: undefined as number | undefined,
  city: "",
});

const fromData1 = reactive({
  name: "李四",
  home: "",
  age: undefined as number | undefined,
  sex: undefined as number | undefined,
  hobby: [] as number[],
  education: undefined as number | undefined,
  way: undefined as number | undefined,
});

const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入姓名" }],
  home: [{ required: true, message: "请输入个人主页地址" }],
  // age: [{ required: true, message: "请输入年龄" }],
  sex: [{ required: true, message: "请选择性别" }],
});

const cityArr = ref();
setTimeout(() => {
  cityArr.value = [
    { label: "上海", value: 1 },
    { label: "北京", value: 2 },
    { label: "广州", value: 3 },
    { label: "深圳", value: 4 },
  ];
  console.log("城市模拟异步加载完成");
  // 手动刷新表单配置
  formRef.value?.refreshConfig();
}, 2000);

const formItems = reactive<FormItem<typeof formData>[]>([
  {
    // 外部异步数据
    ...itemType(ElSelect, { placeholder: "请选择城市" }),
    key: "city",
    label: "城市",
    options: () => cityArr.value,
  },
  {
    ...itemType(ElInput, { placeholder: "请输入姓名" }),
    key: "name",
    label: "姓名",
  },
  {
    ...itemType(ElInput, {
      placeholder: "请输入主页地址",
    }),
    key: "home",
    label: "个人主页",
    slot: {
      prepend: () => "https://",
    },
  },
  {
    ...itemType(ElInput, {
      placeholder: "请输入年龄",
    }),
    key: "age",
    span: 12,
    label: "年龄",
  },
  {
    ...itemType(ElSelect, (data) => {
      return {
        disabled: !data?.age ? true : data?.age < 18,
      };
    }),
    key: "sex",
    label: "性别",
    span: 12,
    options: [
      { label: "男", value: 1 },
      { label: "女", value: 2 },
    ],
  },
  {
    ...itemType(ElRadioGroup),
    key: "education",
    label: "学历",
    options: (data) => {
      if (!data.age || data.age <= 6) {
        // 初始选项
        return [{ label: "幼儿园", value: 1 }];
      } else if (data?.age > 6 && data?.age <= 12) {
        return [
          { label: "幼儿园", value: 1 },
          { label: "小学", value: 2 },
          { label: "初中", value: 3 },
        ];
      } else {
        return [
          { label: "幼儿园", value: 1 },
          { label: "小学", value: 2 },
          { label: "初中", value: 3 },
          { label: "高中", value: 4 },
          { label: "大专", value: 5 },
          { label: "本科", value: 6 },
        ];
      }
    },
  },
  {
    ...itemType(ElCheckboxGroup),
    key: "hobby",
    label: "爱好",
    show: (data) => (data.education ? (data.education as number) >= 2 : false),
    options: () => [
      { label: "吃饭", value: 1 },
      { label: "睡觉", value: 2 },
      { label: "打豆豆", value: 3 },
      { label: "角色扮演", value: 4 },
    ],
  },
  {
    ...itemType(ElSelect, { placeholder: "请选择你使用的武器" }),
    key: "way",
    label: "用什么武器",
    slot: {
      header: () => "请选择",
    },
    show: (data) => (data.hobby ? data.hobby.includes(3) : false),
    options: (data) => {
      if (data.hobby.includes(3) && !data.hobby.includes(4)) {
        return {
          getOptions: () => {
            return new Promise((resolve) => {
              setTimeout(() => {
                resolve([
                  { label: "剑", value: 1 },
                  { label: "枪", value: 2 },
                  { label: "斧", value: 3 },
                ]);
              }, 1000);
            });
          },
          key: "way1",
        };
      } else if (data.hobby.includes(3) && data.hobby.includes(4)) {
        return {
          getOptions: () => {
            return new Promise((resolve) => {
              setTimeout(() => {
                resolve([
                  { label: "剑", value: 1 },
                  { label: "枪", value: 2 },
                  { label: "斧", value: 3 },
                  { label: "步枪", value: 4 },
                  { label: "手枪", value: 5 },
                  { label: "匕首", value: 6 },
                  { label: "火箭筒", value: 7 },
                ]);
              }, 1000);
            });
          },
          key: "way2",
        };
      } else {
        return {
          getOptions: () => {
            return new Promise((resolve) => {
              resolve([]);
            });
          },
          key: "null",
        };
      }
    },
  },
]);

const validate = () => {
  formRef.value?.validate().then((valid) => {
    console.log(formData);

    ElMessage({
      message: valid ? "表单验证成功" : "表单验证失败",
      type: valid ? "success" : "error",
    });
  });
};
const resetFields = () => {
  formRef.value?.resetFields();
};

const newformData = reactive({ ...fromData1 });
const openFormDialog = () => {
  openDialog(
    DynamicForm,
    {
      model: fromData1,
      rules: rules,
      formItems: formItems,
    },
    {
      title: "表单",
      width: "500px",
      showRestFormButton: true,
      onConfirm: (done) => {
        setTimeout(() => {
          console.log(fromData1);
          done();
        }, 3000);
      },
    },
    (ref) => {
      return h(
        ElButton,
        {
          onClick: () => {
            console.log(ref.value);
            ref.value.resetFields?.();
          },
        },
        () => "额外按钮"
      );
    }
  );
};
const openFormDialog1 = () => {
  const check = ref(false);
  openDialog(
    h("div", { style: { color: "red" } }, "测试对话框"),
    {},
    {
      title: "表单",
      width: "500px",
      onConfirm: (done) => {
        setTimeout(() => {
          const random = Math.random();
          if (random < 0.5) {
            ElMessage.error("提交失败，随机数小于0.5");
            done(false);
            return;
          }
          ElMessage.success("提交成功");
          done();
        }, 1000);
      },
    },
    () => {
      return h(
        ElButton,
        {
          onClick: () => {
            ElMessage.info("测试通过允许提交");
            check.value = true;
          },
        },
        () => "额外按钮"
      );
    }
  );
};
</script>

<style scoped>
.dynamic-form {
  display: flex;
  flex-direction: column;
  width: 500px;
  height: 50%;
  margin: auto;
  /* text-align:left ; */
  /* align-items: flex-start; */
  /* justifyItems: left; */
  /* text-align: left; */
}
.test-css {
  color: red;
}
</style>
